﻿using ERPPublic;
using FinancialManagement.Application.Command;
using FinancialManagement.Domain.DTO;
using FinancialManagement.Domain.Model;
using FinancialManagement.Dtos;
using FinancialManagement.Infrstructre.Interface;
using MediatR;
using Newtonsoft.Json;
using NPOI.OpenXmlFormats.Wordprocessing;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Asn1.X509;
using SqlSugar;
using static ERPPublic.ParseAPI;

namespace FinancialManagement.Application.CommandHandler
{
    public class SaleProfitCommandHandlers:IRequestHandler<SaleProfitCommand,PageDto<SaleProfitDTO>>
    {
         ISaleContractRepository saleContract;
         ISaleContractProductRepository saleContractProduct;

        public SaleProfitCommandHandlers(ISaleContractRepository saleContract, ISaleContractProductRepository saleContractProduct)
        {
            this.saleContract = saleContract;
            this.saleContractProduct = saleContractProduct;
        }

        public async Task<PageDto<SaleProfitDTO>> Handle(SaleProfitCommand request, CancellationToken cancellationToken)
        {
            List<OutShipment> outship = await GetOutShipment(1, 100);
            List<Ship> ship = await GetShipMnet(1, 100);
            var salecontiract = (from a in await saleContract.GetAllAsyns() where a.IsDel == false select a).ToList();
            var salecontractproduct = (from a in await saleContractProduct.GetAllAsyns() select a).ToList();
            var list = (from a in salecontiract
                        join b in salecontractproduct on a.SCcontractNumber equals b.SCcontractNumber
                        join c in ship on 
                        a.SaleContractId equals c.SaleContractProductId
                       
                        group new { a,b,c } by 
                        new { 
                            a.SCcontractNumber, 
                            a.ClientName,
                            a.SaleContractId, a.PreferentialPrice,
                            a.RelevancyIName,
                            a.SCcontractPrice,
                            a.SCNum,
                            a.SCPreferentialPrice ,
                            a.SCSalespeople ,
                            a.SCTax ,
                            c.ProNum,
                            c.ShipState,
                            a.ContractTopic ,
                            c.SRANumber

                        } into g
                        select new SaleProfitDTO
                        {
                            SaleContractId = g.Key.SaleContractId,
                            ContractTopic = g.Key.ContractTopic,
                            ClientName = g.Key.ClientName,
                            PreferentialPrice = g.Key.PreferentialPrice,
                            RelevancyIName = g.Key.RelevancyIName,
                            SCcontractNumber = g.Key.SCcontractNumber,
                            SCcontractPrice = g.Key.SCcontractPrice,
                            SCNum = g.Key.SCNum,
                            SCPreferentialPrice = g.Key.SCPreferentialPrice,
                            SCSalespeople = g.Key.SCSalespeople,
                            SCTax = g.Key.SCTax,
                            ProNum = g.Key.ProNum,
                            SCShipmentState = g.Key.ShipState,



                        }).ToList();
            int totalcount = list.Count();
            int  pagecount = (int)Math.Ceiling(totalcount *1.0/ request.pageSize);

            PageDto<SaleProfitDTO> dto = new PageDto<SaleProfitDTO>()
            {
                pcount = pagecount,
                lcount = totalcount,
                list = list.OrderBy(x => x.SaleContractId).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList()
            };
            return dto;

        }

        /// <summary>
        /// 出库单查询
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetOutShipment(int pageIndex, int pageSize)
        {

            var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MSIsInNpZCI6IjE4NjcwOTU3MzQ0NjIwNTg0OTYiLCJqdGkiOiI1MGYyMWRmZS0yNWQ3LTQ1OTQtOTg1Yi0wZTM2MDhhZjJiNmYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMTkiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5bCP576OIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvdXJpIjoiLyIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0.ZjkGj2IxuBzKmF5ZuSyWXQW8TkVqBGLUDkJ86RSweFI";
            HttpClientWrapper client = new HttpClientWrapper(token);

            string name = "http://116.205.121.197:8000/erpck/api/OutboundShipments/ProcureEnquiryShow?pageindex=" + pageIndex + "&pageszie=" + pageSize;

            var respone = await client.GetAsync(name);
            var json = JsonConvert.DeserializeObject<ApiResultList<OutShipment>>(respone);
            return json.data.list;

        }

        /// <summary>
        /// 发货单
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public async Task<dynamic> GetShipMnet(int pageIndex,int pageSize)
        {
            var token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI1MSIsInNpZCI6IjE4NjcwOTU3MzQ0NjIwNTg0OTYiLCJqdGkiOiI1MGYyMWRmZS0yNWQ3LTQ1OTQtOTg1Yi0wZTM2MDhhZjJiNmYiLCJodHRwOi8vc2NoZW1hcy5taWNyb3NvZnQuY29tL3dzLzIwMDgvMDYvaWRlbnRpdHkvY2xhaW1zL2dyb3Vwc2lkIjoiMTkiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoi5bCP576OIiwiaHR0cDovL3NjaGVtYXMueG1sc29hcC5vcmcvd3MvMjAwNS8wNS9pZGVudGl0eS9jbGFpbXMvdXJpIjoiLyIsImlzcyI6IlJlbmFvYm8yMDA0IiwiYXVkIjoiV2VpZnV3dTIyMDNBIn0.ZjkGj2IxuBzKmF5ZuSyWXQW8TkVqBGLUDkJ86RSweFI";
            HttpClientWrapper client = new HttpClientWrapper(token);

            string name = "http://116.205.121.197:8000/erpck/api/Ship/GetShipApplyListCount?pageIndex=" + pageIndex + "&pageSize=" + pageSize;

            var respone = await client.GetAsync(name);
            var json = JsonConvert.DeserializeObject<ApiResultList<Ship>>(respone);
            return json.data.list;
        }




        /// <summary>
        /// 出库单
        /// </summary>
        public class OutShipment
        {
            /// <summary>
            /// 仓库出库id
            /// </summary>
            public int OutboundRequestId { get; set; }
            /// <summary>
            /// 出库编号
            /// </summary>
            public string? OutboundNumber { get; set; }
            /// <summary>
            /// 出库类别
            /// </summary>
            public string? OROutType { get; set; }
            /// <summary>
            /// 出库状态
            /// </summary>
            public int? ORIsState { get; set; }
        }

        /// <summary>
        /// 发货单
        /// </summary>
        public class Ship
        {
            /// <summary>
            /// 发货申请id
            /// </summary>
            [SugarColumn(IsIdentity = true, IsPrimaryKey = true)]
            public int ShippRequestAppId { get; set; }

            /// <summary>
            /// 单据编号
            /// </summary>
            public string? SRANumber { get; set; }
            /// <summary>
            /// 发货状态
            /// </summary>
            public int? ShipState { get; set; }
            /// <summary>
            /// 发货类型(0是销售，1是采购退货)s
            /// </summary>
            public int? ShipType { get; set; }
            /// <summary>
            /// 销售合同id
            /// </summary>
            public int? SaleContractProductId { get; set; }

            public int? ProNum { get; set; }

        }

    }
}
